﻿using Config;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using UI.TestModule;
using System.IO;
using Communication.Model.speedData;
using Communication.Model.netPacket;
using Communication.Model.packetType;
using Communication.Model.displacement;
using Communication.Model.acceleration;
using Communication.Model.configuration;
using Communication.Model.slowSignal;
using Communication.TcpIpService;
using Communication.Model.speedRealTVol;
using Communication.Interface;
using UI.Models;

namespace UI
{
    public partial class MainForm : Form
    {
        #region 成员变量
        Dictionary<int, ChannelType> TypeDictionary = new Dictionary<int, ChannelType>()
        { { 0, ChannelType.Displacement}, { 1, ChannelType.None },{ 2, ChannelType.Acceleration} };
        //private TreeNode config;
        Settings settings = new Settings();
        //通信类
        //ClientManager _iCommunicationService = new ClientManager();
        ICommunicationService _iCommunicationService = new CommunicationService();

        string IP = "127.0.0.1";
        int Port = 3000;
        int dpt_point_num = 1024;
        //实时数据
        SpeedData speed_now = new SpeedData();
        //数据存储
        int FlagSave = 0;
        string PathSave = "";
        //0:监测模式；1：测试模式
        int Mode = 0;
        //0000 0000结束数据
        //0000 0001开始数据
        //0000 0010调试模式
        //0000 0000运行模式（结束数据）
        byte ModeEnable = 0x00;
        TestHelper testHelper = new TestHelper();
        TestForm testForm = null;
        //图谱坐标
        AxisYUnit axisYUnit = AxisYUnit.db;

        //选择的测点
        int testpoint = 1;
        #endregion

        public MainForm()
        {
            InitializeComponent();
            //config = DAQ;
            //Initial(DAQ);
            Initial();
        }
        private void Initial()
        {
            //chart1.ChartAreas[1].CursorX.IsUserSelectionEnabled = true;
            //chart1.ChartAreas[1].Axes[0].Minimum = 1;
            //chart1.ChartAreas[1].Axes[0].Maximum = 200;
            ////游标1
            //float[] cursor1_x = new float[128];
            //float[] cursor1_y = new float[128];
            //Random rd = new Random();
            //for (int i=0;i<cursor1_x.Length;i++)
            //{
            //    cursor1_x[i] = i; 
            //    cursor1_y[i] = rd.Next(0, 100);
            //}
            //chart1.Series[1].Points.DataBindXY(cursor1_x, cursor1_y);
            ////游标2
            //float[] cursor2_x = new float[] { 1000, 1000 };
            //float[] cursor2_y = new float[] { 0, 100 };
            //chart1.Series[3].Points.DataBindXY(cursor2_x, cursor2_y);
            //chart1.ChartAreas[1].CursorX.SetSelectionPosition(1, 100);
            cb_filter.SelectedIndex = 0;
            cb_orbitID.SelectedIndex = 0;
        }
        public void UpdateGeneral()
        {

        }
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void 加载配置文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            string file = "";
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "配置文件(*.xml)|*.xml";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = dialog.FileName;
            }
            bool Loaded = settings.Open(file);
            if (Loaded)
            {
                settings.Path = file;
                //初始化各个界面
                SetGeneral();
                SetChartForm();
                SetConfigForm();
                SetDataGridForm();
                SetOctaveForm();
                //使能按钮
                menuStrip1.Items[1].Enabled = true;
                IP = settings.SystemSet.IP;
                Port = settings.SystemSet.Port;
            }
        }
        private void SetGeneral()
        {
            for (int i = 0; i < 32; i++)
            {
                Control ctrl = tableLayoutPanel1.Controls[i];
                int type = settings.ChannelConfig.Omaplchannels.Channels[i].SensorType;
                //ctrl.Text = i.ToString();
                if (type == 0)
                {
                    string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName + "\r\n";
                    //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                    SetControlText(ctrl, name);
                }
                else
                {
                    string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName + "\r\n";
                    //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                    SetControlText(ctrl, name);
                }
            }
            for (int i = 0; i < 6; i++)
            {
                Control ctrl = tableLayoutPanel1.Controls[i + 32];
                string name = settings.ChannelConfig.omplconfig_rotationchannels.Channels[i].ChannelName + "\r\n";
                //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                SetControlText(ctrl, name);
            }
        }
        private void SetChartForm()
        {
            comboBox1.Items.Clear();
            int count = settings.ChannelConfig.Omaplchannels.Channels.Count;
            for (int i = 0; i < count; i++)
            {
                string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                comboBox1.Items.Add(name);
            }
            comboBox1.SelectedIndex = 0;
            //chart1.ChartAreas.Clear();
        }
        private void SetOctaveForm()
        {
            cb_octave.Items.Clear();
            int count = settings.ChannelConfig.Omaplchannels.Channels.Count;
            for (int i = 0; i < count; i++)
            {
                if (settings.ChannelConfig.Omaplchannels.Channels[i].SensorType == 2)
                {
                    string id = settings.ChannelConfig.Omaplchannels.Channels[i].No.ToString();
                    string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                    cb_octave.Items.Add(id + ":" + name);
                }
            }
            cb_octave.SelectedIndex = 0;
        }
        private void SetConfigForm()
        {
            //振动通道配置
            listBox1.Items.Clear();
            int count = settings.ChannelConfig.Omaplchannels.Channels.Count;
            for (int i = 0; i < count; i++)
            {
                string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                listBox1.Items.Add(name);
            }
            listBox1.SelectedIndex = 0;

            //转速通道配置
            listBox2.Items.Clear();
            count = settings.ChannelConfig.omplconfig_rotationchannels.Channels.Count;
            for (int i = 0; i < count; i++)
            {
                string name = settings.ChannelConfig.omplconfig_rotationchannels.Channels[i].ChannelName;
                listBox2.Items.Add(name);
            }
            listBox2.SelectedIndex = 0;
        }
        /// <summary>
        /// 更新配置界面的内容
        /// </summary>
        private void UpdateConfigForm()
        {
            this.Invoke((EventHandler)delegate
            {
                //更新振动通道配置信息
                int index = listBox1.SelectedIndex;
                if (index >= 0)
                {
                    //基本信息
                    SetControlText(tb_id, settings.ChannelConfig.Omaplchannels.Channels[index].No.ToString());
                    SetControlText(tb_name, settings.ChannelConfig.Omaplchannels.Channels[index].ChannelName);
                    SetControlText(tb_angle, settings.ChannelConfig.Omaplchannels.Channels[index].FixAngle.ToString());
                    SetComboIndex(cb_rpm, settings.ChannelConfig.Omaplchannels.Channels[index].SpeedNo - 1);

                    //传感器信息
                    int type = settings.ChannelConfig.Omaplchannels.Channels[index].SensorType;
                    //SetControlText(textBox6, sensorType[type]);
                    SetComboIndex(cb_sensorType, settings.ChannelConfig.Omaplchannels.Channels[index].SensorType);
                    SetControlText(tb_sensitivity, settings.ChannelConfig.Omaplchannels.Channels[index].Sensitivity.ToString());
                    SetControlText(tb_offset, settings.ChannelConfig.Omaplchannels.Channels[index].PianYiLiang.ToString());

                    //报警信息
                    if (type == 0)//位移通道
                    {
                        //隐藏加速度通道配置内容
                        sc_alarm.Panel1.Hide();
                        sc_alarm.Panel2.Show();
                        //更新数据
                        tb_all_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Warning.ToString();
                        tb_all_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Alarm.ToString();
                        enable_all.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].Enable != 0 ? true : false;

                        tb_1x_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency1Warning.ToString();
                        tb_1x_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency1Alarm.ToString();
                        enable_1x.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency1Enable != 0 ? true : false;

                        tb_2x_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency2Warning.ToString();
                        tb_2x_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency2Alarm.ToString();
                        enable_2x.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].Frequency2Enable != 0 ? true : false;

                        tb_half_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].FrequencyHalfWarning.ToString();
                        tb_half_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].FrequencyHalfAlarm.ToString();
                        enable_half.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].FrequencyHalfEnable != 0 ? true : false;
                    }
                    else//加速度通道
                    {
                        //隐藏位移通道的报警设置内容
                        sc_alarm.Panel1.Show();
                        sc_alarm.Panel2.Hide();

                        //更新数据
                        tb_total_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccTotalAmplitudeYellowValue.ToString();
                        tb_total_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccTotalAmplitudeRedValue.ToString();
                        enable_total.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].AccTotalAmplitudeValueIsUser != 0 ? true : false;

                        tb_low_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccLowAmplitudeYellowValue.ToString();
                        tb_low_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccLowAmplitudeRedValue.ToString();
                        enable_low.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].AccLowAmplitudeValueIsUser != 0 ? true : false;

                        tb_high_warning.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccHighAmplitudeYellowValue.ToString();
                        tb_high_alarm.Text = settings.ChannelConfig.Omaplchannels.Channels[index].AccHighAmplitudeRedValue.ToString();
                        enable_high.Checked = settings.ChannelConfig.Omaplchannels.Channels[index].AccHighAmplitudeValueIsUser != 0 ? true : false;
                    }
                }
                //更新转速通道配置信息
                int id = listBox2.SelectedIndex;
                if (id >= 0)
                {
                    SetControlText(tb_rpm_name, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChannelName);
                    //SetControlText(tb_rpm_angle, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].an);
                    SetComboIndex(cb_rpm_direction, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].rationdir);
                    rb_key_manual.Checked = (settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCao == 1);
                    rb_key_auto.Checked = (settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCaoAuto == 1);
                    rb_gear_auto.Checked = (settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanAuto == 1);
                    rb_gear_manual.Checked = (settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPan == 1);
                    SetControlText(tb_key_voltage, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCaoVolCompare.ToString());
                    SetControlText(tb_gear_num, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanNum.ToString());
                    SetControlText(tb_gear_voltage, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanCompareVol.ToString());
                    SetControlText(tb_rpm_virtual, settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].VirtualSpeed.ToString());
                }
                //更新系统配置
                SetControlText(tb_IP, settings.SystemSet.IP);
                SetControlText(tb_Port, settings.SystemSet.Port.ToString());
            });

        }
        private void SetDataGridForm()
        {
            //初始化位移列表
            dataGridView1.Columns.Add("id", "通道ID");
            dataGridView1.Columns.Add("name", "通道名称");
            dataGridView1.Columns.Add("rpm", "转速");
            dataGridView1.Columns.Add("p2p", "峰峰值");
            dataGridView1.Columns.Add("gapvoltage", "间隙电压");
            dataGridView1.Columns.Add("rms", "平方根值");
            dataGridView1.Columns.Add("1xA", "一倍频幅值");
            dataGridView1.Columns.Add("1xP", "一倍频相位");
            dataGridView1.Columns.Add("2xA", "二倍频幅值");
            dataGridView1.Columns.Add("2xP", "二倍频相位");
            dataGridView1.Columns.Add("halfxA", "半频幅值");
            dataGridView1.Columns.Add("halfxP", "半频相位");
            dataGridView1.Rows.Add(16);

            //初始化振动加速度列表
            dataGridView2.Columns.Add("id", "通道ID");
            dataGridView2.Columns.Add("name", "通道名称");
            dataGridView2.Columns.Add("rpm", "转速");
            dataGridView2.Columns.Add("TotalDB", "振动总值");
            dataGridView2.Columns.Add("highDB", "高频总值");
            dataGridView2.Columns.Add("lowDB", "低频总值");
            dataGridView2.Columns.Add("velocityRMS", "速度均方根值");
            dataGridView2.Columns.Add("AverageVol", "平均电压");
            dataGridView2.Columns.Add("displacementRMS", "位移均方根值");
            dataGridView2.Columns.Add("1xA", "一倍频幅值");
            dataGridView2.Columns.Add("2xA", "二倍频幅值");
            dataGridView2.Columns.Add("3xA", "三倍频幅值");
            dataGridView2.Rows.Add(16);

            int count = settings.ChannelConfig.Omaplchannels.Channels.Count;
            for (int i = 0; i < count; i++)
            {
                int No = settings.ChannelConfig.Omaplchannels.Channels[i].No;
                string name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                if (i < 16)
                {
                    dataGridView1.Rows[i].Cells["id"].Value = No.ToString();
                    dataGridView1.Rows[i].Cells["name"].Value = name;
                }
                else
                {
                    dataGridView2.Rows[i - 16].Cells["id"].Value = No.ToString();
                    dataGridView2.Rows[i - 16].Cells["name"].Value = name;
                }

            }
        }
        private void SetControlText(Control ctrl, string name)
        {
            if (ctrl.IsHandleCreated && ctrl.InvokeRequired)
            {
                ctrl.Invoke(new Action<Control, string>(SetControlText), ctrl, name);
                return;
            }
            ctrl.Text = name;
        }
        private void SetComboIndex(ComboBox ctrl, int index)
        {
            if (ctrl.IsHandleCreated && ctrl.InvokeRequired)
            {
                ctrl.Invoke(new Action<ComboBox, int>(SetComboIndex), ctrl, index);
                return;
            }
            if (index >= 0)
                ctrl.SelectedIndex = index;
        }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void 连接硬件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IP = settings.SystemSet.IP;
            Port = settings.SystemSet.Port;
            bool isConnnected = _iCommunicationService.Connect2Server(IP, Port);

            if (isConnnected)
            {
                _iCommunicationService.AddDataHandler(onDataReceived);
                _iCommunicationService.StartData();
                //_iCommunicationService.GetNetPacket += GetNetPakcetHandler;
                //_iCommunicationService.GetDisplacement += ReceivedDispalcement;
                //_iCommunicationService.GetAccData += ReceivedAccData;
                //_iCommunicationService.GetConfig += ReceivedConfig;
                //_iCommunicationService.GetSpeed += ReceivedSpeedData;
                //_iCommunicationService.GetSpeedVol += ReceivedSpeedVol;
                //_iCommunicationService.GetString += ReceivedString;
                //_iCommunicationService.GetSlowSignal += ReceivedSlowSignal;
                //_iCommunicationService.GetMachineTime += ReceiveMachineTime;
                menuStrip1.Items[2].Enabled = true;
            }
        }
        /// <summary>
        /// 收到采集数据
        /// </summary>
        /// <param name="netPacket"></param>
        private void GetNetPakcetHandler(NetPacket packet)
        {
            //存储公有信息

            //更新总貌图
            UpdateGeneral(packet);
            //更新图表

            //更新数据列表

        }
        /// <summary>
        /// 更新总貌图
        /// </summary>
        /// <param name="packet"></param>
        private void UpdateGeneral(NetPacket packet)
        {
            switch (packet.NetPacketHead.PacketType)
            {
                case PacketType.STRING:
                    //Console.WriteLine(packet.Data.ToString());
                    SetControlText(label39, packet.DataPacket.ToString());
                    break;
                //case PacketType.ACQParametersConfig:
                //    ACQParametersConfig acq = (ACQParametersConfig)packet.DataPacket;

                //    break;
                case PacketType.DisplacementPacket:
                    DisplacementData dpt = (DisplacementData)packet.DataPacket;
                    for (int i = 0; i < 16; i++)
                    {
                        Control ctrl = tableLayoutPanel1.Controls[i];
                        string text = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName + "\r\n\r\n";
                        text += "峰峰值: " + dpt.CHDisData[i].PK2PK.ToString("0.0000") + "\r\n";
                        text += "间隙电压: " + dpt.CHDisData[i].GapVoltage.ToString("0.0000") + "\r\n";
                        //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                        SetControlText(ctrl, text);
                    }
                    break;
                case PacketType.AccelerationPacket:
                    AccData acc = (AccData)packet.DataPacket;
                    for (int i = 0; i < 16; i++)
                    {
                        Control ctrl = tableLayoutPanel1.Controls[i + 16];
                        string text = settings.ChannelConfig.Omaplchannels.Channels[i + 16].ChannelName + "\r\n\r\n";
                        text += "振动总值: " + acc.CHAccData[i].TotalDB.ToString("0.0000") + "\r\n";
                        text += "平均电压: " + acc.CHAccData[i].AverageVol.ToString("0.0000") + "\r\n";
                        //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                        SetControlText(ctrl, text);
                    }
                    break;
                case PacketType.SpeedPacket:
                    SpeedData speed = (SpeedData)packet.DataPacket;
                    for (int i = 0; i < 6; i++)
                    {
                        Control ctrl = tableLayoutPanel1.Controls[i + 32];
                        string text = settings.ChannelConfig.omplconfig_rotationchannels.Channels[i].ChannelName + "\r\n\r\n";
                        text += "转速" + i.ToString() + speed.ChSpeeds[i].rpm.ToString("0.0") + "\r\n";
                        //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                        SetControlText(ctrl, text);
                    }
                    break;
                case PacketType.SpeedVoltagePacket:
                    SpeedRealTVol speedVol = (SpeedRealTVol)packet.DataPacket;

                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 收到数据后，更新图谱
        /// </summary>
        /// <param name="packet"></param>
        private void UpdateChart(int type)
        {
            //if (chart1.IsHandleCreated && chart1.InvokeRequired)
            //{
            //    chart1.Invoke(new Action<>(SetComboIndex));
            //    return;
            //}

        }
        private void ReceivedString(string msg)
        {
            //更新总貌图
            SetControlText(label39, msg);
        }
        private void ReceivedDispalcement(DisplacementData dpt)
        {
            //存储达到全局静态变量中
            GlobalVariable.DptCurrent = dpt;
            this.Invoke((EventHandler)delegate
            {
                //更新总貌图位移 
                if (tabControl_main.SelectedIndex == 0)
                {
                    for (int i = 0; i < 32; i++)
                    {
                        int type = settings.ChannelConfig.Omaplchannels.Channels[i].SensorType;
                        //位移通道
                        if (type == 0)
                        {
                            Control ctrl = tableLayoutPanel1.Controls[i];
                            string text = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName + "\r\n\r\n";
                            text += "峰峰值: " + dpt.CHDisData[i].PK2PK.ToString("0.0000") + "um\r\n";
                            text += "间隙电压: " + dpt.CHDisData[i].GapVoltage.ToString("0.0000") + "mA\r\n";
                            //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                            SetControlText(ctrl, text);
                        }
                    }
                }
                //更新图
                else if (tabControl_main.SelectedIndex == 1)
                {
                    int select = comboBox1.SelectedIndex;
                    int type = settings.ChannelConfig.Omaplchannels.Channels[select].SensorType;
                    if (type == 0)
                    {
                        //两个ChartAera设置可见
                        chart1.ChartAreas[0].Visible = true;
                        chart1.ChartAreas[0].Axes[0].Minimum = 0;
                        chart1.ChartAreas[0].Axes[0].Maximum = 1023;
                        chart1.ChartAreas[0].Axes[0].Interval = 100;
                        //chart1.ChartAreas[0].Axes[0].MajorGrid.Interval = System.Double.NaN;
                        //chart1.ChartAreas[0].Axes[1].MajorGrid.Interval = System.Double.NaN;


                        int index = comboBox1.SelectedIndex;
                        float[] time = dpt.CHDisData[index].ZDs;
                        float[] amps = dpt.CHDisData[index].Amps;
                        chart1.Series[0].Color = Color.Red;
                        chart1.Series[0].Points.DataBindY(time);

                        chart1.Series[1].Color = Color.Red;
                        int num = (int)dpt_point_num / 2;
                        float[] axisX = new float[num];
                        for (int i = 0; i < num; i++)
                        {
                            axisX[i] = i;
                        }

                        int rpm_index = settings.ChannelConfig.Omaplchannels.Channels[select].SpeedNo;
                        //根据转速求横坐标
                        if (speed_now.ChSpeeds != null)
                        {
                            string text = "转速" + rpm_index.ToString() + ": " + speed_now.ChSpeeds[rpm_index - 1].rpm.ToString("0.0");
                            float rpm = speed_now.ChSpeeds[rpm_index - 1].rpm;
                            SetControlText(label41, text);
                            if (rpm > 5)
                            {
                                double fs = rpm / 60.0 * 64;
                                double df = fs / dpt_point_num;
                                for (int i = 0; i < num; i++)
                                {
                                    axisX[i] = Convert.ToSingle(i * df);
                                }
                            }
                        }
                        //设置下方图表样式
                        chart1.ChartAreas[1].Visible = true;
                        chart1.ChartAreas[1].Axes[0].IsLogarithmic = false;
                        chart1.ChartAreas[1].Axes[0].Minimum = 1;
                        chart1.ChartAreas[1].Axes[0].Maximum = axisX[num - 1];
                        chart1.ChartAreas[1].Axes[0].MajorGrid.Enabled = true;
                        chart1.ChartAreas[1].Axes[0].MajorGrid.Interval = 100;
                        chart1.ChartAreas[1].Axes[0].MinorGrid.Enabled = false;
                        chart1.ChartAreas[1].Axes[0].MinorTickMark.Enabled = false;                        //绑定数据

                        chart1.Series[1].Points.DataBindXY(axisX, amps);
                        //求区间内的最大值点
                        DataPoint dp = getMaxPoint(chart1.Series[1].Points, chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd);
                        if (dp != null)
                        {
                            //画出最大值点
                            //chart1.Series[2].Points.Clear();
                            chart1.Series[2].Points.DataBindXY(new double[] { dp.XValue }, new double[] { dp.YValues[0] });
                            //显示游标值
                            SetControlText(label67, string.Format("{0:F2}Hz-{1:F2}Hz最大值",
                            chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd));
                            //显示区间内最大值
                            SetControlText(textBox2, string.Format("{0:F2}um@{1:F2}Hz", dp.YValues[0], dp.XValue));
                        }
                    }
                }
                //更新轴心轨迹
                else if (tabControl_main.SelectedIndex == 4)
                {
                    ////测点ID
                    //testpoint = cb_orbitID.SelectedIndex;
                    ////显示轴心轨迹合成曲线
                    //chart_orbit.Series[0].Points.DataBindXY
                    //(dpt.OrbitData[testpoint].xCoordinate, dpt.OrbitData[testpoint].yCoordinate);
                    ////轴心轨迹信号
                    //chart_orbit_x.Series[0].Points.DataBindY(dpt.OrbitData[testpoint].xCoordinate);
                    //chart_orbit_y.Series[0].Points.DataBindY(dpt.OrbitData[testpoint].yCoordinate);

                    ////显示轴心位置
                    //SetControlText(label_startx, "startX= " + dpt.OrbitData[testpoint].startX.ToString("F2"));
                    //SetControlText(label_starty, "startY= " + dpt.OrbitData[testpoint].startY.ToString("F2"));
                    //SetControlText(label_endx, "CurrentX= " + dpt.OrbitData[testpoint].currentX.ToString("F2"));
                    //SetControlText(label_endy, "CurrentY= " + dpt.OrbitData[testpoint].currentY.ToString("F2"));
                }
                else { }
            });

        }
        private void ReceivedAccData(AccData acc)
        {
            try
            {
                //存储到全局静态变量中
                GlobalVariable.AccCurrent = acc;
                this.Invoke((EventHandler)delegate
                {
                    //更新总貌图加速度          
                    if (tabControl_main.SelectedIndex == 0)
                    {
                        for (int i = 0; i < 32; i++)
                        {
                            int type = settings.ChannelConfig.Omaplchannels.Channels[i].SensorType;
                            //加速度通道
                            if (type == 2)
                            {
                                Control ctrl = tableLayoutPanel1.Controls[i];
                                string text = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName + "\r\n\r\n";
                                text += "振动总值: " + acc.CHAccData[i].TotalDB.ToString("0.0000") + "dB\r\n";
                                text += "平均电压: " + acc.CHAccData[i].AverageVol.ToString("0.0000") + "V\r\n";
                                //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                                SetControlText(ctrl, text);
                            }
                        }
                    }
                    //更新图
                    else if (tabControl_main.SelectedIndex == 1)
                    {
                        int select = comboBox1.SelectedIndex;
                        int type = settings.ChannelConfig.Omaplchannels.Channels[select].SensorType;
                        //两个ChartAera设置可见
                        if (type == 2)
                        {
                            chart1.ChartAreas[0].Visible = false;
                            chart1.ChartAreas[1].Visible = true;
                            //chart1.ChartAreas[1].Axes[0].IsLogarithmic = true;
                            float[] valueY = acc.CHAccData[select].FFTAmpDB;
                            switch (axisYUnit)
                            {
                                case AxisYUnit.ms2:
                                    valueY = acc.CHAccData[select].FFTAmp;
                                    break;
                                default:
                                    break;
                            }
                            float[] x = new float[65536];
                            for (int i = 0; i < x.Length; i++)
                            {
                                x[i] = (i) * 25600.0f / 131072.0f;
                                //data[i] = Convert.ToSingle(Math.Log10(data[i]) * 20 + 120.0f);
                            }
                            chart1.ChartAreas[1].Axes[0].IsLogarithmic = true;
                            chart1.ChartAreas[1].Axes[0].Minimum = 1;
                            chart1.ChartAreas[1].Axes[0].Maximum = 12800;
                            chart1.ChartAreas[1].Axes[0].Interval = System.Double.NaN;
                            //chart1.ChartAreas[1].Axes[0].Interval = 10;
                            chart1.ChartAreas[1].Axes[0].MajorGrid.Enabled = true;
                            chart1.ChartAreas[1].Axes[0].MajorGrid.Interval = 1;
                            chart1.ChartAreas[1].Axes[0].MinorGrid.Enabled = true;
                            chart1.ChartAreas[1].Axes[0].MinorGrid.Interval = 1;
                            //chart1.ChartAreas[1].Axes[0].MajorGrid.Enabled = true;
                            //chart1.ChartAreas[1].Axes[0].MajorGrid.Interval = 0.1;
                            chart1.Series[1].Color = Color.Red;
                            chart1.Series[1].Points.DataBindXY(x, valueY);

                            int rpm_index = settings.ChannelConfig.Omaplchannels.Channels[select].SpeedNo;
                            if (speed_now.ChSpeeds != null)
                            {
                                string text = "转速" + rpm_index.ToString() + ": " + speed_now.ChSpeeds[rpm_index - 1].rpm.ToString("0.0");
                                SetControlText(label41, text);
                            }
                            DataPoint dp = getMaxPoint(chart1.Series[1].Points, chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd);
                            if (dp != null)
                            {
                                //画出最大值点
                                //chart1.Series[2].Points.Clear();
                                chart1.Series[2].Points.DataBindXY(new double[] { dp.XValue }, new double[] { dp.YValues[0] });
                                //显示游标值
                                SetControlText(label67, string.Format("{0:F2}Hz-{1:F2}Hz最大值",
                                    chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd));
                                //显示区间内最大值
                                SetControlText(textBox2, string.Format("{0:F2}@{1:F2}Hz", dp.YValues[0], dp.XValue));
                            }
                        }

                    }
                    //更新数据列表
                    else if (tabControl_main.SelectedIndex == 2 && tabControl3.SelectedIndex == 1)
                    {
                        DataTable dt = new DataTable();
                    }
                    else if (tabControl_main.SelectedIndex == 5)
                    {
                        float[] octave = Helper.OctaveHelper.CalculateOctave_1_3();
                        string[] octaves = octave.Select(p => Math.Round(p).ToString("f0")).ToArray();
                        int id = int.Parse(cb_octave.SelectedItem.ToString().Split(':')[0]);
                        float[] values = acc.CHAccData[id]._1_3otcaveDB.Select(p => (float)Math.Round(p)).ToArray();
                        //柱状图
                        //chart_octave.Series[0].Points.DataBindXY(octave, acc.CHAccData[id]._1_3otcaveDB);
                        chart_octave.Series[0].Points.DataBindXY(octaves, acc.CHAccData[id]._1_3otcaveDB);
                        //chart_octave.Series[0].Points.DataBindY(acc.CHAccData[id]._1_3otcaveDB);
                        //绑定
                        for (int i = 0; i < 31; i++)
                        {
                            datagrid_octave.Rows.Add();
                            datagrid_octave.Rows[i].Cells["Freq"].Value = octaves[i];
                            datagrid_octave.Rows[i].Cells["Amp"].Value = values[i].ToString();
                        }
                    }
                    else
                    {

                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        private void ReceivedConfig(ACQParametersConfig config)
        {

        }
        public void ReceivedSpeedData(SpeedData speed)
        {
            this.Invoke((EventHandler)delegate
            {
                //存储实时转速
                speed_now = speed;
                string content = DateTime.Now.ToString() + ",";
                //更新总貌图转速
                for (int i = 0; i < 6; i++)
                {
                    Control ctrl = tableLayoutPanel1.Controls[i + 32];
                    string text = settings.ChannelConfig.omplconfig_rotationchannels.Channels[i].ChannelName + "\r\n\r\n";
                    text += "转速" + (i + 1).ToString() + ": " + speed.ChSpeeds[i].rpm.ToString("0.0") + "\r\n";
                    //name = settings.ChannelConfig.Omaplchannels.Channels[i].ChannelName;
                    SetControlText(ctrl, text);
                    content += speed.ChSpeeds[i].rpm.ToString("0.00");
                    content += ",";
                }
                if (FlagSave != 0)
                {
                    if (PathSave != "")
                    {
                        TxtOperate.AppendLine(PathSave, content);
                    }
                }
            });
        }
        public void ReceivedSpeedVol(SpeedRealTVol data)
        {
            this.Invoke((EventHandler)delegate
            {
                if (tabControl2.SelectedIndex == 2 && tabControl_main.SelectedIndex == 3)
                {
                    int id = listBox2.SelectedIndex;
                    SetControlText(tb_key_max, data.ChVols[id].TopVolt.ToString());
                    SetControlText(tb_key_min, data.ChVols[id].BotmVolt.ToString());
                    SetControlText(tb_gear_max, data.ChVols[id].TopVolt.ToString());
                    SetControlText(tb_gear_min, data.ChVols[id].BotmVolt.ToString());
                }
            });
        }
        private void ReceiveMachineTime(MachineTime machineTime)
        {
            this.Invoke((EventHandler)delegate
            {
                int Year = Convert.ToInt32(machineTime.Year);
                int Month = Convert.ToInt32(machineTime.Month);
                int Day = Convert.ToInt32(machineTime.Day);
                int Hour = Convert.ToInt32(machineTime.Hour);
                int Minute = Convert.ToInt32(machineTime.Minute);
                int Second = Convert.ToInt32(machineTime.Second);
                DateTime time = new DateTime(Year, Month, Day, Hour, Minute, Second);

                Status_time.Text = time.ToString();
            });
        }
        private void ReceivedSlowSignal(SlowSignal ss)
        {

        }
        private void kaiToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 开始数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _iCommunicationService.StartData();
            menuStrip1.Items[3].Enabled = true;
            ModeEnable = Convert.ToByte(ModeEnable | 0b00000001);
            if ((ModeEnable & 0b00000011) == 3)
                menuStrip1.Items[4].Enabled = true;
        }

        private void 结束数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _iCommunicationService.StopData();
            menuStrip1.Items[3].Enabled = false;
            ModeEnable = Convert.ToByte(ModeEnable & 0b11111110);
        }

        private void 调试模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _iCommunicationService.DebugMode();
            ModeEnable = Convert.ToByte(ModeEnable | 0b00000010);
            if ((ModeEnable & 0b00000011) == 3)
                menuStrip1.Items[4].Enabled = true;
        }

        private void label42_Click(object sender, EventArgs e)
        {

        }

        private void tabPage9_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 应用修改的配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            #region 【更新振动通道配置内容】
            //--基本信息
            int id = listBox1.SelectedIndex;
            settings.ChannelConfig.Omaplchannels.Channels[id].ChannelName = tb_name.Text;
            settings.ChannelConfig.Omaplchannels.Channels[id].FixAngle = float.Parse(tb_angle.Text);
            settings.ChannelConfig.Omaplchannels.Channels[id].SpeedNo = cb_rpm.SelectedIndex + 1;
            //--传感器信息
            settings.ChannelConfig.Omaplchannels.Channels[id].SensorType = cb_sensorType.SelectedIndex;
            settings.ChannelConfig.Omaplchannels.Channels[id].Sensitivity = float.Parse(tb_sensitivity.Text);
            settings.ChannelConfig.Omaplchannels.Channels[id].PianYiLiang = float.Parse(tb_offset.Text);
            //--报警信息
            int type = cb_sensorType.SelectedIndex;
            if (type == 0)//位移通道报警信息设置
            {
                //更新数据
                settings.ChannelConfig.Omaplchannels.Channels[id].Warning = float.Parse(tb_all_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Alarm = float.Parse(tb_all_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Enable = enable_all.Checked ? 1 : 0;

                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency1Warning = float.Parse(tb_1x_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency1Alarm = float.Parse(tb_1x_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency1Enable = enable_1x.Checked ? 1 : 0;

                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency2Warning = float.Parse(tb_2x_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency2Alarm = float.Parse(tb_2x_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].Frequency2Enable = enable_2x.Checked ? 1 : 0;

                settings.ChannelConfig.Omaplchannels.Channels[id].FrequencyHalfWarning = float.Parse(tb_half_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].FrequencyHalfAlarm = float.Parse(tb_half_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].FrequencyHalfEnable = enable_half.Checked ? 1 : 0;
            }
            else//加速度通道报警信息设置
            {
                settings.ChannelConfig.Omaplchannels.Channels[id].AccTotalAmplitudeYellowValue = float.Parse(tb_total_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccTotalAmplitudeRedValue = float.Parse(tb_total_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccTotalAmplitudeValueIsUser = enable_total.Checked ? 1 : 0;

                settings.ChannelConfig.Omaplchannels.Channels[id].AccLowAmplitudeYellowValue = float.Parse(tb_low_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccLowAmplitudeRedValue = float.Parse(tb_low_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccLowAmplitudeValueIsUser = enable_low.Checked ? 1 : 0;

                settings.ChannelConfig.Omaplchannels.Channels[id].AccHighAmplitudeYellowValue = float.Parse(tb_high_warning.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccHighAmplitudeRedValue = float.Parse(tb_high_alarm.Text);
                settings.ChannelConfig.Omaplchannels.Channels[id].AccHighAmplitudeValueIsUser = enable_high.Checked ? 1 : 0;
            }

            #endregion
            //更新转速通道配置文件
            id = listBox2.SelectedIndex;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChannelName = tb_rpm_name.Text;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].rationdir = cb_rpm_direction.SelectedIndex;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCaoVolCompare = float.Parse(tb_key_voltage.Text);
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanNum = int.Parse(tb_gear_num.Text);
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanCompareVol = float.Parse(tb_gear_voltage.Text);
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCao = rb_key_manual.Checked ? 1 : 0;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].JianXiangCaoAuto = rb_key_auto.Checked ? 1 : 0;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPan = rb_gear_manual.Checked ? 1 : 0;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].ChiLunPanAuto = rb_gear_auto.Checked ? 1 : 0;
            settings.ChannelConfig.omplconfig_rotationchannels.Channels[id].VirtualSpeed = float.Parse(tb_rpm_virtual.Text);
            //更新系统配置
            settings.SystemSet.IP = tb_IP.Text;
            settings.SystemSet.Port = int.Parse(tb_Port.Text);
            //保存文件
            settings.saveXml(settings.Path);
            //更新各个图标
            SetGeneral();
            SetChartForm();
            SetConfigForm();
            SetDataGridForm();
            SetOctaveForm();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateConfigForm();
        }
        /// <summary>
        /// 向下位机传输配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string uploadPath = settings.SystemSet.UploadFilePath;
            string userName = settings.SystemSet.UserName;
            string key = settings.SystemSet.Key;
            FtpService ftp = new FtpService(IP.ToString(), uploadPath, userName, key);
            ftp.UploadFile(settings.Path);
        }



        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateConfigForm();
        }


        private void 设置虚拟转速ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //_iCommunicationService.sendString("192.168.2.64", "SetVisualRate");
        }

        private void 运行模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _iCommunicationService.RunMode();
            ModeEnable = Convert.ToByte(ModeEnable & 11111101);
        }

        private void label39_Click(object sender, EventArgs e)
        {

        }

        private void label40_Click(object sender, EventArgs e)
        {

        }
        //鼠标左键按下：设置选择区域的start坐标
        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            chart1.ChartAreas[1].CursorX.SelectionStart = chart1.ChartAreas[1].CursorX.Position;
            chart1.ChartAreas[1].CursorX.SelectionEnd = chart1.ChartAreas[1].CursorX.SelectionStart;
        }
        //鼠标左键抬起：设置选择区域的end坐标
        private void chart1_MouseUp(object sender, MouseEventArgs e)
        {
            chart1.ChartAreas[1].CursorX.SelectionEnd = chart1.ChartAreas[1].CursorX.Position;
            DataPoint dp = getMaxPoint(chart1.Series[1].Points, chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd);
            if (dp != null)
            {
                //画出最大值点
                //chart1.Series[2].Points.Clear();
                chart1.Series[2].Points.DataBindXY(new double[] { dp.XValue }, new double[] { dp.YValues[0] });
                //显示游标值
                SetControlText(label67, string.Format("{0:F2}Hz-{1:F2}Hz最大值",
                    chart1.ChartAreas[1].CursorX.SelectionStart, chart1.ChartAreas[1].CursorX.SelectionEnd));
                //显示区间内最大值
                SetControlText(textBox2, string.Format("{0:F2}dB@{1:F2}Hz", dp.YValues[0], dp.XValue));
            }
        }
        //chart1.GetToolTipText += new EventHandler<ToolTipEventArgs>(chart_GetToolTipText);
        void chart_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)
            {
                int i = e.HitTestResult.PointIndex;
                DataPoint dp = e.HitTestResult.Series.Points[i];
                e.Text = string.Format("{1:F3}", dp.XValue, dp.YValues[0]);
            }
        }
        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            HitTestResult hit = chart1.HitTest(e.X, e.Y);
            if (hit.ChartElementType == ChartElementType.DataPoint)
            {
                if (hit.Series.ChartArea == "ChartArea2")
                {
                    this.Cursor = Cursors.Cross;
                    int i = hit.PointIndex;
                    DataPoint dp = hit.Series.Points[i];

                    double doubleXValue = (dp.XValue);
                    double doubleYValue = dp.YValues[0];
                    //光标
                    hit.ChartArea.CursorX.SetCursorPosition(dp.XValue);
                    //自我实现值的显示       
                    //e.Text = string.Format("{1:F3}", dp.XValue, dp.YValues[0]);
                    textBox1.Text = string.Format("{0:F2}db@{1:F2}Hz", dp.YValues[0], dp.XValue);
                    chart1.Series[1].Points[i].ToolTip = string.Format("{0:F2}db@{1:F2}Hz", dp.YValues[0], dp.XValue);
                    //chart1.Series[1].ToolTip.
                }
            }
            else
            {
                this.Cursor = Cursors.Default;
            }

        }

        private DataPoint getMaxPoint(DataPointCollection dpc, double min, double max)
        {
            if (max > min)
            {
                DataPoint MaxPoint = new DataPoint();
                int n = dpc.Count;
                //找到大于min的最小点的索引
                int start = FindIndex(dpc, min);
                //找到小于max的最大点的索引
                int end = FindIndex(dpc, max);
                MaxPoint = dpc[start];
                for (int i = start; i < max; i++)
                {
                    if (MaxPoint.YValues[0] < dpc[i].YValues[0])
                        MaxPoint = dpc[i];
                }
                return MaxPoint;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 找到增长序列data中大于taget的索引最小的点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        private int FindIndex(DataPointCollection dpc, double target)
        {
            int left = 0;
            int right = dpc.Count - 1;
            while (left <= right)
            {
                int mid = (left + right) / 2;
                if (dpc[mid].XValue > target)
                {
                    right = mid - 1;
                }
                else if (dpc[mid].XValue <= target)
                {
                    left = mid + 1;
                }
            }
            return left;
        }

        private void label71_Click(object sender, EventArgs e)
        {

        }

        private void 设置时间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TimeSet timeForm = new TimeSet(_iCommunicationService);
            //timeForm.Show();

        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateConfigForm();
        }

        private void 指令ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 开始存储数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FlagSave = 1;
            OpenFileDialog dialog = new OpenFileDialog();
            string file = "";
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = dialog.FileName;
            }
            PathSave = file;
        }

        private void 结束存储数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FlagSave = 0;
        }

        private void 进入测试模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Mode = 1;
            //MessageBox.Show("请选择测试通道");
            menuStrip1.Items[4].BackColor = Color.LightBlue;
        }

        private void 退出测试模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Mode = 0;
            testHelper.Clear();
            for (int i = 0; i < 32; i++)
            {
                Control ctrl = tableLayoutPanel1.Controls[i];
                SetContrlColor(ctrl, Color.White);
            }
            menuStrip1.Items[4].BackColor = Color.White;
        }
        private void LabelClicked(object sender, EventArgs e)
        {
            if (Mode == 1 && (ModeEnable & 0b00000011) == 3)
            {
                int id = Convert.ToInt32((sender as Label).Name.Remove(0, 5)) - 1;
                if (id < GlobalVariable.ChannelNum)
                {
                    if (!testHelper.IsChoosed(id))
                    {
                        (sender as Label).BackColor = Color.LightBlue;
                        int type = settings.ChannelConfig.Omaplchannels.Channels[id].SensorType;
                        StringReader sr = new StringReader((sender as Label).Text);
                        testHelper.ChooseChannel(id, sr.ReadLine(), TypeDictionary[type]);
                    }
                    //没被选中
                    //if (!testHelper.IsChecked[id])
                    //{
                    //    (sender as Label).BackColor = Color.LightBlue;
                    //    testHelper.IsChecked[id] = !testHelper.IsChecked[id];
                    //}
                    //选中
                    //else
                    //{
                    //    (sender as Label).BackColor = Color.White;
                    //    testHelper.IsChecked[id] = !testHelper.IsChecked[id];
                    //}
                }

            }

        }
        private void SetContrlColor(Control ctrl, Color color)
        {
            if (ctrl.IsHandleCreated && ctrl.InvokeRequired)
            {
                ctrl.Invoke(new Action<Control, Color>(SetContrlColor), ctrl, color);
                return;
            }
            ctrl.BackColor = color;
        }

        private void 开始测试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            testForm = new TestForm(testHelper.TestCHList);
            testForm.Show();
        }

        private void cb_orbitID_SelectedIndexChanged(object sender, EventArgs e)
        {
            testpoint = cb_orbitID.SelectedIndex + 1;
            //发送配置指令
        }

        private void cb_filter_SelectedIndexChanged(object sender, EventArgs e)
        {
            //发送配置指令
        }

        private void datagrid_octave_1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void onDataReceived(NetPacket netPacket)
        {
            //cm.GetDisplacement += ReceivedDispalcement;
            //cm.GetAccData += ReceivedAccData;
            //cm.GetConfig += ReceivedConfig;
            //cm.GetSpeed += ReceivedSpeedData;
            //cm.GetSpeedVol += ReceivedSpeedVol;
            //cm.GetString += ReceivedString;
            //cm.GetSlowSignal += ReceivedSlowSignal;
            //cm.GetMachineTime += ReceiveMachineTime;
            try
            {
                //存储最新的转速包，给DisplacementModel中的字段赋值
                SpeedData rpmsPacket = new SpeedData();
                DateTime time = DateTime.Now;

                switch (netPacket.NetPacketHead.PacketType)
                {
                    case PacketType.DisplacementPacket:
                        #region 接收到位移数据的处理流程
                        //通讯结构体
                        DisplacementData dpt = (DisplacementData)netPacket.DataPacket;
                        ReceivedDispalcement(dpt);

                        #endregion
                        break;
                    case PacketType.AccelerationPacket:
                        //通讯结构体
                        AccData acc = (AccData)netPacket.DataPacket;
                        ReceivedAccData(acc);

                        break;
                    case PacketType.SpeedPacket:
                        //通讯结构体
                        rpmsPacket = (SpeedData)netPacket.DataPacket;
                        ReceivedSpeedData(rpmsPacket);

                        break;
                }
            }
            catch (Exception ex)
            {

                throw;
            }


        }

        private void dbToolStripMenuItem_Click(object sender, EventArgs e)
        {
            axisYUnit = AxisYUnit.db;
        }

        private void ms2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            axisYUnit = AxisYUnit.ms2;
        }
    }

    public class TxtOperate
    {
        public static void AppendLine(string path, string content)
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine(content);
            //sw.Write(content);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
    }


}
